package com.wyl.libbase.utils;

import android.widget.TextView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

import java.util.concurrent.TimeUnit;

/**
 * 项目名称：o2o
 * 创建人：江心才子
 * 创建时间：2019-08-06 16:51
 * 内容描述：
 * 修改说明：
 */
public class CountDownUtils {
    /**
     * 倒计时控件使用
     *
     * @param textView
     * @param time
     * @param message
     */
    public static void changeBtnUi(final TextView textView, final int time, final String message) {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(time + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) {
                        return time - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        textView.setClickable(false);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        textView.setText(String.valueOf(aLong));
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        textView.setClickable(true);
                        textView.setText(message);
                    }
                });
    }

    /**
     * 延迟执行任务
     *
     * @param seconds 延迟时间
     * @param task
     */
    public static void delay(int seconds, final Runnable task) {
        Observable.timer(seconds, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        task.run();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
